package com.sy.controller;

import com.sy.dto.JsonResult;
import com.sy.entity.Blog;
import com.sy.entity.CategoryCollection;
import com.sy.service.BlogService;
import com.sy.utils.HttpUtils;
import com.sy.utils.RandomUtils;
import com.sy.utils.RedisClient;
import com.sy.vo.CategoryBlogParams;
import org.apache.commons.io.FilenameUtils;
import com.sy.vo.UserBlogParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

import static com.sy.constant.BusinessConstant.*;


@RestController
public class BlogController {
    @Autowired
    private RedisClient redisClient;


    @Value("${uploadDir}")
    private String uploadDir;

    @Value("${uploadServiceDir}")
    private String uploadServiceDir;

    @Value("${callBackPath}")
    private String callBackPath;

    @Autowired
    private BlogService blogService;
    @Autowired(required = false)
    private HttpServletResponse res;
    @Autowired
    private HttpUtils httpUtils;


    /**
     * 根据博客分类id查询相关博客信息
     * @param params
     * @return
     */
    @RequestMapping(value = "/categories/blogs" , method = RequestMethod.POST)
    public JsonResult getNavBlogInfos(@RequestBody CategoryBlogParams params){
        JsonResult result = null;
        Integer categoryType = params.getCategoryType();
        if(categoryType == BLOG_CATEGORY_TYPE_FIRST){
            result = blogService.getNavBlogInfos(params.getCategoryId());
            res.setStatus(result.getCode());
        }else if (categoryType == BLOG_CATEGORY_TYPE_SECOND) {
            result = blogService.getBlogsByCategoryId(params.getCategoryId());
            res.setStatus(result.getCode());
        }
        return result;
    }

    @RequestMapping(value = "/blogs/user/{userId}" , method = RequestMethod.POST)
    public JsonResult getUserByBlogId(@PathVariable("userId") Integer userId){
        JsonResult result =  blogService.getUserByBlogId(userId);
        res.setStatus(result.getCode());
        return result;
    }


    @RequestMapping(value = "/hotest" , method = RequestMethod.GET)
    public JsonResult getHotestBlog(){
        JsonResult result = blogService.getHotestBlog();
        res.setStatus(result.getCode());
        return result;
    }
    @RequestMapping(value = "/thumbs" , method = RequestMethod.GET)
    public JsonResult getThumbsBlog(){
        JsonResult result = blogService.getThumbsBlog();
        res.setStatus(result.getCode());
        return result;
    }

    @RequestMapping(value = "/collects" , method = RequestMethod.GET)
    public JsonResult getCollectCountBlog(){
        JsonResult result = blogService.getCollectCountBlog();
        res.setStatus(result.getCode());
        return result;
    }


    @GetMapping("/blogs/{blogId}")
    public JsonResult getDetailBlogInfo(@PathVariable("blogId") Integer blogId){
        JsonResult result = blogService.getDetailBlogInfo(blogId);
        res.setStatus(result.getCode());
        return result;
    }

    @PostMapping("/imgs")
    @ResponseBody
    public JsonResult formOne(MultipartFile file, HttpServletResponse response,Integer uploadMode) throws IOException {
        //文件的原始名称

        JsonResult result = new JsonResult();
        String submittedFileName = file.getOriginalFilename();
        String url = "";

        //在上传文件的时候，不要使用文件的默认的名字来作为最终保存的名字，因为
        //后续的文件在上传过程中有可能会和之前的文件重名，发生覆盖，因此文件一般都需要重命名
        String newFileName = RandomUtils.getUuid();
        //获取原来文件的后缀名
        String extName = FilenameUtils.getExtension(submittedFileName);
        //最终的新的文件的完整名字=新的文件名+.+原来的后缀
        newFileName = newFileName + "." + extName;

        //判断用于保存文件的目录是否存在，如果不存在则创建之
        File saveDir = new File(uploadDir);

        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }

        try (InputStream is = file.getInputStream()) {
            OutputStream os = new FileOutputStream(uploadDir + newFileName);
            System.out.println(uploadDir + newFileName);
            //将输入流复制到输出流即完成了文件的拷贝操作
            FileCopyUtils.copy(is, os);
        }

        //单文件上传组件
        if (uploadMode == 0){
            System.out.println("执行单文件上传组件");
            response.sendRedirect(callBackPath+"?error=0&url="+uploadServiceDir+newFileName);
        }


        //存储文件名到redis用户对比

        //获取用户id
        // TODO: 2021/1/15 获取当前请求的用户id
        System.out.println("-------------执行文件名缓存操作");
        Integer userid = 15;

        String blogImgName = newFileName;
        String redisKey = REDIS_BLOG_IMGS_CACHE+userid;

        //存入redis等待对比
        redisClient.sadd(redisKey,blogImgName);
        System.out.println("-------------缓存完成");

        //文件上传后的访问路径
        result.setData(uploadServiceDir+newFileName);
        result.setCode(201);

        //设置返回状态码
        response.setStatus(result.getCode());



        return result;

    }

    /**
     *@功能：上传博客到数据库
     *
     *1.删除文件服务器中 由于编辑器退格操作删除的图片而多余的图
     *2.根据用户id存储 博客标题 博客内容
     *
     *@方法（）：
     */
    @PostMapping("/blogs")
    @ResponseBody
    public JsonResult updataBlog(@RequestBody UserBlogParams userBlogParams, HttpServletResponse response){
        Blog blog = new Blog();

        /**
         * 处理前端数据
         * */
        //博客表中数据
        blog.setTitle(userBlogParams.getTitle());
        blog.setContent(userBlogParams.getHtml());
        blog.setCreated(userBlogParams.getCreated());
        blog.setUserId(httpUtils.getLoginUser().getId());
        blog.setIsDraft(userBlogParams.getIsDraft().byteValue());
        if(userBlogParams.getIsDraft()!=0){
            blog.setIsOriginal(userBlogParams.getTypeId().byteValue());
            blog.setOriginalLink(userBlogParams.getOriginalLink());
        }


        JsonResult result = blogService.loadBlog(blog,userBlogParams.getLabel());
        response.setStatus(result.getCode());
        return result;
    }




}
